package kaist.sep521.lego.circlebicycle;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;

public class CircleInfoActivity extends Activity {
	private static String name = null;
	private TextView circleName = null;
	private TextView circleDesc = null;
	private TextView circleMember = null;
	private Group gInfo = new Group();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_circle_info);

		circleName = (TextView)findViewById(R.id.circleinfo_name);
		circleDesc = (TextView)findViewById(R.id.circleinfo_desc);
		circleMember = (TextView)findViewById(R.id.circleinfo_member);

		Intent intent = getIntent();
		name = intent.getExtras().getString("name").toString();
	}

	@Override
	protected void onResume() {
		super.onResume();
		updateInfo(name);
	}

	private void updateInfo(String name) {
		// get Group info from server
		gInfo = queryGroupInfo(name);

		circleName.setText(gInfo.getName());

		if ( gInfo.getInfo() != null ) {
			circleDesc.setText(gInfo.getInfo());
		}

		String userList = null;
		if ( gInfo.getMember() != null ) {
			for (int i=0 ; i < gInfo.getMember().size() ; i++) {
				if (userList == null)
					userList = gInfo.getMember().get(i);
				else
					userList = userList + ", " + gInfo.getMember().get(i);
			}	
		}

		circleMember.setText(userList);
	}


	private Group queryGroupInfo(String groupname) {
		Group info = new Group();
		try {
			String xml = "http://14.63.196.253/~lego/groupinfo.php?group=" + groupname;
			URL url = new URL(xml);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();

				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();
				GroupInfoParserHandler iHandler = new GroupInfoParserHandler();
				xr.setContentHandler(iHandler);
				xr.parse(new InputSource(is));
				info = iHandler.getParsedData();
			} else {
				Toast.makeText(this, "Server connection error!!", Toast.LENGTH_SHORT).show();
			}
			conn.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return info;
	}
}
